<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/2/7
 * Time: 18:56.
 */

declare(strict_types=1);

namespace App\Application\Admin\Service;

use App\Application\Admin\Model\Roomlabel;

use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Context\Context;
use Hyperf\Database\Model\Relations\Relation;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Cache\Listener\DeleteListenerEvent;
use Hyperf\Stringable\Str;
use Psr\EventDispatcher\EventDispatcherInterface;
use function Hyperf\Config\config;


class RoomService
{

    protected array $all_roomlabel = [];
    protected array $menu_list = [];

    #[Inject]
    protected EventDispatcherInterface $dispatcher;

    /**
     * 不需要校验的权限集合
     *
     * @var string[]
     */
    protected $not_auth = [];

    private function __construct()
    {
        $this->not_auth = config('room.not_auth');
    }

    static function getInstance(): self
    {
        return Context::getOrSet(self::class, function () {
            return new self();
        });
    }

    /**
     * 获取所有菜单
     *
     * @return array
     */
    public function getAllroom(): array
    {
        if (empty($this->all_roomlabel)) {
            $this->all_roomlabel = $this->getAllroomTree();
        }

        return $this->all_roomlabel;
    }

    #[Cacheable(prefix: "room", ttl: 0, listener: "room-update")]
    private function getAllroomTree(int $parent_roomlabel_id = 0): array
    {
        return Roomlabel::where('deleted_at', null)
//            ->with([
//                'children' => function (Relation $relation) {
//                    $relation->with(['children']);
//                }
//            ])
            ->orderBy('created_at')
            ->select([
                'room_id', 'name'
            ])
            ->get()
            ->toArray();
    }

    /**
     * 更新权限列表
     */
    public function updatelabel()
    {
        //清空缓存
        $this->dispatcher->dispatch(new DeleteListenerEvent('room-update', ['parent_room_id' => 0]));
    }
}